package fun.werfamily.wf.user.core.domain.util;

import com.alibaba.fastjson.JSON;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import fun.werfamily.wf.user.core.domain.constant.RedisConstant;
import fun.werfamily.wf.user.core.domain.constant.RedisTimeoutConstants;
import fun.werfamily.wf.user.core.domain.enums.SmsTemplateEnum;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Random;

/**
 * @Author: Mr.WenMing Zhang
 * @Date: 2022/07/26 14:55
 * @Description:
 **/
@Component
@Slf4j
public class SmsMessageUtil {
    @Resource
    private RedisUtil redisUtil;

    private static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    public Boolean sendVerifyCode(String phone, SmsTemplateEnum smsTemplateEnum) {
        Random random = new Random();
        Integer randomCode = random.nextInt(999999);
        com.aliyun.dysmsapi20170525.Client client = null;
        try {
            client = SmsMessageUtil.createClient("LTAI4G96XivpFtcN3ZAfEt2D", "iZClnELxFITYXlNBLmEklONH56Hzzd");
        } catch (Exception e) {
            e.printStackTrace();
        }
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName("E家部落")
                .setTemplateCode(smsTemplateEnum.getTemplateCode())
                .setPhoneNumbers(phone)
                .setTemplateParam("{\"code\":\"" + randomCode + "\"}");
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);
            log.info("发送短信返回{}", JSON.toJSONString(sendSmsResponse));
            redisUtil.saveString(RedisConstant.VERIFY_CODE + smsTemplateEnum.getTemplateCode() + ":" + phone, randomCode.toString(), RedisTimeoutConstants.CACHE_HOLD_TIME_5M);
            return Boolean.TRUE;
        } catch (TeaException error) {
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return Boolean.FALSE;
    }
}
